package com.springBoot.springBootSysCore.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.springBoot.springBootSysCore.common.comment.annotation.AddComment;
import com.springBoot.springBootSysCore.common.comment.annotation.CommentBase;
import com.springBoot.springBootSysCore.interceptor.LogInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.springBoot.springBootSysCore.filter.SessionFilter;
import com.springBoot.springBootSysCore.filter.WebSiteMeshFilter;

import javax.servlet.MultipartConfigElement;

@Configuration
//@AutoConfigureAfter(shiroconfig.class)
public class WebConfig extends WebMvcConfigurerAdapter{
    /**
     * 异常未 MultipartException
     * 文件上传配置
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大
        factory.setMaxFileSize("1024MB"); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("10240MB");
        return factory.createMultipartConfig();
    }
//    @Bean
//    public EmbeddedServletContainerCustomizer containerCustomizer() {
//        return new EmbeddedServletContainerCustomizer() {
//            @Override
//            public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
//                configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
//                configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400"));
//                configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
//                configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(java.lang.Throwable.class, "/error/500")); }
//        };
//    }

//   实体类 @JSONField(serialize=false)
//    @Bean
//    public HttpMessageConverters fastJsonHttpMessageConverters() {
//        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//        FastJsonConfig fastJsonConfig = new FastJsonConfig();
//        fastJsonConfig.setSerializerFeatures(
//                SerializerFeature.PrettyFormat,
//                SerializerFeature.WriteDateUseDateFormat,
//                SerializerFeature.WriteNullStringAsEmpty,
//                SerializerFeature.WriteNullListAsEmpty,
//                SerializerFeature.WriteNullNumberAsZero,
//                SerializerFeature.WriteNullBooleanAsFalse,
//                SerializerFeature.IgnoreNonFieldGetter);
//        fastConverter.setFastJsonConfig(fastJsonConfig);
//        HttpMessageConverter<?> converter = fastConverter;
//        return new HttpMessageConverters(converter);
//    }

    /**
     * 装饰器  
     * @return  
     * 2016年8月27日下午12:37:20  
     */  
    @Bean  
    public FilterRegistrationBean siteMeshFilter(){
        //FILTER 要注意如果一个设置了order 其他的也要设置order 否则会出现问题
        FilterRegistrationBean fitler = new FilterRegistrationBean();  
        WebSiteMeshFilter siteMeshFilter = new WebSiteMeshFilter();  
        fitler.setFilter(siteMeshFilter);
        fitler.setOrder(2);
        return fitler;
    }
    /**
     * 会话拦截
     * @return
     */
    @Bean
    public FilterRegistrationBean sessionFilter(){
        FilterRegistrationBean fitler = new FilterRegistrationBean();
        SessionFilter sessionFilter = new SessionFilter();
        fitler.setFilter(sessionFilter);
        fitler.setOrder(1);
        return fitler;
    }
    /**
     * 解决跨域问题
     * @return
     */
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置你要允许的网站域名，如果全允许则设为 *
        config.addAllowedOrigin("*");
        // 如果要限制 HEADER 或 METHOD 请自行更改
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        // 这个顺序很重要哦，为避免麻烦请设置在最前
        bean.setOrder(0);
        return bean;
    }

//    @Bean
//    public CommentBase commentBase(){
//        return  new CommentBase();
//    }
//    @Bean
//    public AddComment addComment(CommentBase commentBase){
//        return  new AddComment(commentBase);
//    }

    /**
     * 日志拦截
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }



    @Value("${adminPath}")
	protected String adminPath;
    /**
     * 定义默认首页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        registry.addViewController("/").setViewName("forward:/"+adminPath+"/login");
    	registry.addViewController("/").setViewName("redirect:"+adminPath+"/login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }

    //    @Override
//    public  void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//        converters.clear();
//        converters.add(new MappingJackson2HttpMessageConverter());
//
//        List<MediaType> supportedMediaTypes = new ArrayList<>();
//        supportedMediaTypes.add(MediaType.ALL);
//        StringHttpMessageConverter c = new StringHttpMessageConverter(Charset.forName("UTF-8"));
//        c.setSupportedMediaTypes(supportedMediaTypes);
//        converters.add(c);
//
//        converters.add(new ByteArrayHttpMessageConverter());
//    }
   
}  
